<template>
    <div class="mime-video-detail-wrap">
      <div class="mime-video" ref="mimeVideo">
        <video id="video-player-container-id" class="player-size" playsinline webkit-playsinline></video>
      </div>
      <div class="mime-video-content">
        <template>
          <van-tabs v-model="active" animated :line-height="lineHeight" color="#0085ca" v-if="singleDouble">
            <van-tab title="内容介绍">
              <div class="videoCont padding-12">
                <h4 class="detail-title">{{videoTitle}}</h4>
                <div class="seeNumCount clearfix">
                  <div>
                    <label class="seeNumCount-icon"></label>
                    {{videoCount}}人观看
                  </div>
                </div>
                <div class="detail-content van-hairline--bottom" v-html="videoContent"></div>
                <div class="video-recommend" v-if="mimeVideoList.length">
                  <h2>为您推荐</h2>
                  <!--推荐视频列表-->
                  <van-row gutter="12">
                    <van-col span="12" v-for="(item,index) in mimeVideoList" :key="index" class="index-list">
                      <div @click="goVideoActive(item.id)">
                        <div class="mime-video-list-container">
                        <div class="mime-video-list-img border-radius5">
                          <img :src="CDNimgUrl + item.image">
                          <template>
                            <span v-if="item.count <= 1">{{item.timer}}</span>
                            <span v-else>共{{item.count}}集</span>
                          </template>
                        </div>
                        <div class="mime-video-list-content">
                          <h4 class="mime-video-list-content-title">{{item.title}}</h4>
                          <van-row>
                            <van-col span='12' class="van-ellipsis">
                              <p>{{item.doctor}}</p>
                            </van-col>
                            <van-col span='12' class="text-align-r">
                              <p>
                                <label class="list-icon-see info-list-icon-see"></label>
                                {{item.clicks > 9999 ? (item.clicks/10000).toFixed(1)+'万' : item.clicks}}人观看
                              </p>
                            </van-col>
                          </van-row>
                        </div>
                      </div>
                      </div>
                    </van-col>
                  </van-row>
                </div>
              </div>
            </van-tab>
            <van-tab :title="'内容列表('+videoSectionNum+')'">
              <div class="videoCont">
                <van-collapse v-model="activeName" accordion>
                  <van-collapse-item v-for="(item,index) in videoChaper" :title="'第'+(index+1)+'章\xa0\xa0'+item.title" :name="index" :key="index">
                    <div v-for="(item2,index2) in item.section" :key="index2" class="video-section-list" @click="playVideo(item2.id)" :class="{'active':listCurrent === item2.id}">
                      <van-row>
                        <van-col span="4">
                          <h6>第{{item2.section_num}}节</h6>
                        </van-col>
                        <van-col span="19" offset="1">
                          <div class="fl">
                            <h4 class="video-section-title">{{item2.title}}</h4>
                            <p class="video-section-time">
                              <i></i>
                              {{item2.timer}}
                            </p>
                          </div>
                          <div class="fr" v-if="listCurrent === item2.id">
                            <label class="bofang-icon"></label>
                          </div>
                        </van-col>
                      </van-row>
                    </div>
                  </van-collapse-item>
                </van-collapse>
              </div>
            </van-tab>
            <van-tab title="评论">
              <div class="videoComment-wrap">
                <van-list
                  v-model="isUploading"
                  :finished="isUpfinished"
                  :finished-text=" commentList.length === 0 ? '暂无评论' : '没有更多了' "
                  @load="onLoad"
                >
                  <ul class="comment-list">
                    <li v-for="(item,index) in commentList" :key="index">
                      <van-row>
                        <van-col span="3">
                          <div class="comment-portrait">
                            <img :src="item.user_avatar">
                          </div>
                        </van-col>
                        <van-col span="20" offset="1">
                          <h5>{{item.user_name}}</h5>
                          <p>{{item.content}}</p>
                          <span>{{item.publish_at}}</span>
                        </van-col>
                      </van-row>
                    </li>
                  </ul>
                </van-list>
              </div>
            </van-tab>
          </van-tabs>
          <div v-if="!singleDouble">
            <div class="videoCont padding-12">
              <h4 class="detail-title">{{videoTitle}}</h4>
              <div class="seeNumCount clearfix">
                <div>
                  <label class="seeNumCount-icon"></label>
                  {{videoCount}}人观看
                </div>
              </div>
              <div class="detail-content van-hairline--bottom" v-html="videoContent"></div>
              <div class="video-recommend" v-if="mimeVideoList.length">
                <h2>为您推荐</h2>
                <!--推荐视频列表-->
                <van-row gutter="12">
                  <van-col span="12" v-for="(item,index) in mimeVideoList" :key="index" class="index-list">
                    <div @click="goVideoActive(item.id)">
                      <div class="mime-video-list-container">
                        <div class="mime-video-list-img border-radius5">
                          <img :src="CDNimgUrl + item.image">
                          <template>
                            <span v-if="item.count <= 1">{{item.timer}}</span>
                            <span v-else>共{{item.count}}集</span>
                          </template>
                        </div>
                        <div class="mime-video-list-content">
                          <h4 class="mime-video-list-content-title">{{item.title}}</h4>
                          <van-row>
                            <van-col span='12' class="van-ellipsis">
                              <p>{{item.doctor}}</p>
                            </van-col>
                            <van-col span='12' class="text-align-r">
                              <p>
                                <label class="list-icon-see info-list-icon-see"></label>
                                {{item.clicks > 9999 ? (item.clicks/10000).toFixed(1)+'万' : item.clicks}}人观看
                              </p>
                            </van-col>
                          </van-row>
                        </div>
                      </div>
                    </div>
                  </van-col>
                </van-row>
              </div>
            </div>
            <!--评论-->
            <div class="videoComment-wrap">
              <h4>评论</h4>
              <van-list
                v-model="isUploading"
                :finished="isUpfinished"
                :finished-text=" commentList.length === 0 ? '暂无评论' : '没有更多了' "
                @load="onLoad"
              >
                <ul class="comment-list">
                  <li v-for="(item,index) in commentList" :key="index">
                    <van-row>
                      <van-col span="3">
                        <div class="comment-portrait">
                          <img :src="item.user_avatar">
                        </div>
                      </van-col>
                      <van-col span="20" offset="1">
                        <h5>{{item.user_name}}</h5>
                        <p>{{item.content}}</p>
                        <span>{{item.publish_at}}</span>
                      </van-col>
                    </van-row>
                </li>
                </ul>
              </van-list>
            </div>
          </div>
        </template>
      </div>
      <!-- 底部-->
      <div class="info-footer">
        <div class="info-foot-wrap">
          <van-row class="text-align-c">
            <van-col span="8">
              <div @click="showCommentMask">
                <div class="div-icon comment-icon"></div>
                <span>{{commentNum}}</span>
              </div>
            </van-col>
            <van-col span="8">
              <div class="div-icon thumps-up-icon" @click="changeStatus" :class="likeStatus ? 'active' : ''"></div>
              <span :class="likeStatus ? 'active' : ''">{{likeNum}}</span>
            </van-col>
            <van-col span="8">
              <div class="div-icon star-icon" @click="starClick" :class="collectStatus ? 'active' : ''"></div>
              <span :class="collectStatus ? 'active' : ''">{{collectedNum}}</span>
            </van-col>
          </van-row>
        </div>
      </div>
      <!--评论遮罩-->
      <div class="comment-mask-wrap" v-if="showComment">
        <div class="comment-mask-contain">
          <div class="comment-mask-close text-align-r">
            <van-icon name="cross" @click="closeCommentMask"/>
          </div>
          <div class="comment-mask-textarea">
            <van-field
              v-model="message"
              type="textarea"
              placeholder="留下自己观点"
              autofocus="autofocus"
              ref="textArea"
            />
          </div>
          <div class="comment-mask-submit text-align-r">
            <van-button type="info" @click="sumbitComment">发送</van-button>
          </div>
        </div>
      </div>
    </div>
</template>

<script>
  import ajax from '../../module/ajax/public'
  import Cookie from 'js-cookie'
  import wxapi from '../../module/wxapi'
  import { Row, Col, Tab, Tabs, Collapse, CollapseItem, Toast, Notify, Button, Field, List , Icon  } from 'vant'

  var player = null
  export default {
      name: "MimeVideoDetail",
      components:{
        [Row.name]: Row,
        [Col.name]: Col,
        [Tab.name]: Tab,
        [Tabs.name]: Tabs,
        [Collapse.name]: Collapse,
        [CollapseItem.name]: CollapseItem,
        [Button.name]: Button,
        [Field.name]: Field,
        [List.name]: List,
        [Icon.name]: Icon,
      },
      mounted(){
        this.id = this.$route.query.id
        this.getVideoData(this.id)
        this.getCommentData()
        this.userInfo = JSON.parse(Cookie.get('userInfo'))
        this.userPortrait = this.userInfo.avatar ? this.userInfo.avatar : '/static/images/user-portrait-default.png'
        this.userName = this.userInfo.nickname ? this.userInfo.nickname : this.userInfo.phone
        wxapi.wxRegister(this.wxRegCallback, window.location.href)
      },
      data(){
          return{
            baseUrl:'mime-video-detail',
            CDNimgUrl: this.GLOBAL.CDNimgUrl,
            id:1,
            videoSrc:'',
            videoTitle:'',
            videoCount:null,
            videoContent:'',
            videoSectionNum:0,
            singleDouble:true,
            videoImg:'',
            videoChaper:[],
            active:0,
            activeName:0,
            mimeVideoList:[],
            lineHeight:2,
            fileID:'',
            appID:'',
            videoIdArray:[],
            nextVideoId:0,
            listCurrent:0,
            time:null,
            likeNum:0,
            likeStatus:false,
            collectStatus:false,
            message:'',
            commentList:[],
            currentTimes:'',
            userInfo:null,
            userName:'',
            userPortrait:'',
            page:0,
            isUploading: false,
            isUpfinished: false,
            showComment:false,
            commentNum:0,
            collectedNum:0
          }
      },
      methods:{
        getVideoData(id){
          ajax.doAction({
            url: '/course/'+id,
            type: 'GET',
            beforeSend:()=> {
              Toast({
                type:'loading',
                duration:0,
                loadingType:'spinner',
                message: '加载中...'
              });
            },
            successCallback:(data)=>{
              // console.log(data)
              let datas = data.data
              this.videoTitle = datas.info.title
              this.videoContent = datas.info.brief
              this.videoCount=datas.info.clicks > 9999 ? (datas.info.clicks/10000).toFixed(1) + '万' : datas.info.clicks
              this.videoImg = this.CDNimgUrl + datas.info.image
              this.likeNum = datas.info.liked_num
              this.collectStatus = datas.info.is_collected
              this.likeStatus = datas.info.is_liked
              this.commentNum = datas.info.comment_num
              this.collectedNum = datas.info.collected_num
              this.mimeVideoList = datas.recommend
              this.videoSectionNum = datas.info.count
              if(datas.info.count === 1){
                this.singleDouble = false
              }else {
                this.singleDouble = true
              }
              this.videoChaper = datas.info.chapters
              if(datas.info.multiSection){
                this.getVideoSource(this.videoChaper[0].section[0].id)
              }else{
                this.getVideoSource(this.videoChaper[0].id)
              }
              this.videoChaper.forEach((value,index)=>{
                value.section.forEach((value1,index1)=>{
                  this.videoIdArray.push(value1.id)
                })
              })
              // console.log(this.videoIdArray)
            },
            complete:()=> {
              Toast.clear()
            },
            errorCallback: (data)=> {
              console.log('请求失败')
            }
          });
        },
        getVideoSource(id){
          ajax.doAction({
            url: '/course-audio/'+id,
            type: 'GET',
            successCallback:(data)=>{
              // console.log(data)
              let datas = data.data
              this.fileID = datas.fileID
              this.appID = datas.appID
              if(player){
                player.dispose()
                this.$refs.mimeVideo.innerHTML='<video id="video-player-container-id" class="player-size" playsinline webkit-playsinline></video>'
              }
              player = TCPlayer('video-player-container-id', { // video-player-container-id 为播放器容器ID，必须与html中一致
                fileID: this.fileID, // 请传入需要播放的视频filID 必须
                appID: this.appID, // 请传入点播账号的appID 必须,
              })
              this.common(id)
              this.listenPlaying(id)
              this.listenPause()
            },
            errorCallback: (data)=> {
              console.log('请求失败')
            }
          });
        },
        //点击播放
        playVideo(id,isFree){
          this.listCurrent = id
          ajax.doAction({
            url: '/course-audio/'+id,
            type: 'GET',
            successCallback:(data)=>{
              // console.log(data);
              let datas = data.data
              this.fileID = datas.fileID
              this.appID = datas.appID
              player.loadVideoByID({
                fileID: this.fileID, // 请传入需要播放的视频 filID 必须
                appID: this.appID, // 请传入点播账号的 appID 必须
              })
              setTimeout(()=>{
                player.play()
              },600);
              this.common(id)
              this.listenPlaying(id)
              this.listenPause()
            },
            errorCallback: (data)=> {
              console.log('请求失败')
            }
          });
        },
        //监听播放事件
        listenPlaying(id){
          player.on('playing',() => {
            this.listCurrent = id
            this.submitStudyRecord(id)
          });
        },
        //监听暂停事件
        listenPause(){
          player.on('pause',() => {
            clearInterval(this.time)
          });
        },
        common(id){
          let currentIndex = this.videoIdArray.indexOf(id)
          if((currentIndex != -1) && (currentIndex < this.videoIdArray.length-1) ){
            this.nextVideoId = this.videoIdArray[currentIndex+1]
          }
          player.on('ended',()=> {
            if(this.nextVideoId){
              return
            }
            this.playVideo(this.nextVideoId)
          });
        },
        //从推荐列表进入另一个课程
        goVideoActive(id){
          this.$router.push({
            path:this.baseUrl,
            query:{
              id:id
            }
          });
          this.getVideoData(id)
        },
        //提交学习记录
        submitStudyRecord(id){
          clearInterval(this.time)
          this.time = setInterval(()=>{
              // console.log(id);
              ajax.doAction({
                url: '/course-study',
                type: 'POST',
                items:{
                  course_id:parseInt(this.id),
                  course_section_id:id,
                  time:player.currentTime(),
                  end:0
                },
                successCallback:(data)=>{
                  console.log('学习记录提交成功')
                },
                errorCallback: (data)=> {
                  console.log('请求失败')
                }
              });
            },60000)
        },
        //点赞
        changeStatus(){
          this.likeStatus = !this.likeStatus
          this.likeNum = this.likeStatus ? parseInt(this.likeNum)+1 : parseInt(this.likeNum)-1
          ajax.doAction({
            url: '/course/'+ this.id +'/like',
            type: 'POST',
            items:{
              status:this.likeStatus
            },
            successCallback:(data)=>{
              // console.log(data);
            },
            errorCallback: (data)=> {
              console.log('请求失败')
            }
          })
        },
        //收藏
        starClick(){
          this.collectStatus = !this.collectStatus
          ajax.doAction({
            url: '/course/'+ this.id +'/collect',
            type: 'POST',
            items:{
              status:this.collectStatus
            },
            successCallback:(data)=>{
              // console.log(data);
            },
            errorCallback: (data)=> {
              console.log('请求失败')
            }
          })
        },
        //评论列表
        getCommentData(){
          this.page++
          ajax.doAction({
            url: `/course/${this.id}/commentList?page=${this.page}`,
            type: 'GET',
            successCallback:(data)=>{
              // console.log(data);
              let datas = data.data;
              this.isUploading = false
              if (datas.length > 0) {
                this.commentList = this.commentList.concat(datas)
              } else {
                this.isUpfinished = true
              }
            },
            errorCallback: (data)=> {
              console.log('请求失败')
            }
          })
        },
        onLoad () {
          // console.log('上拉加载'+this.page);
          this.getCommentData()
        },
        //发表评论
        sumbitComment(){
          ajax.doAction({
            url: '/course/'+ this.id +'/comment',
            type: 'POST',
            items:{
              content:this.message
            },
            successCallback:(data)=>{
              // console.log(data);
              let date1 = new Date()
              let currentDate = date1.toLocaleDateString().split('/').join('-')
              let currentTime = date1.toTimeString().slice(0,5)
              this.currentTimes = currentDate +'\xa0\xa0'+ currentTime
              this.commentList.unshift({
                'user_avatar':this.userPortrait,
                'user_name':this.userName,
                'content':this.message,
                'publish_at':this.currentTimes
              })
              this.message = ''
              this.showComment = false
            },
            errorCallback: (data)=> {
              console.log('请求失败')
            }
          })
        },
        showCommentMask(){
          this.showComment = true
          setTimeout(()=>{
            let textDom = this.$refs.textArea
            textDom.focus()
          },200)
        },
        closeCommentMask(){
          this.showComment = false
        },
        wxRegCallback () {
          // 用于微信JS-SDK回调
          this.wxShareTimeline()
          this.wxShareAppMessage()
        },
        wxShareTimeline () {
          // 微信自定义分享到朋友圈
          let option = {
            title: this.videoTitle, // 分享标题, 请自行替换
            link: window.location.href, // 分享链接，根据自身项目决定是否需要split
            imgUrl: this.videoImg, // 分享图标, 请自行替换，需要绝对路径
            success: () => {
              ajax.doAction({
                url: '/user/shareSuccess',
                type: 'POST',
                successCallback:(data)=>{
                  // console.log(data)
                },
                errorCallback: (data)=> {
                  console.log('请求失败')
                }
              });
            },
            error: () => {
              alert('已取消分享')
            }
          }
          // 将配置注入通用方法
          wxapi.ShareTimeline(option)
        },
        wxShareAppMessage () {
          // 微信自定义分享给朋友
          let option = {
            title: this.videoTitle, // 分享标题, 请自行替换
            // desc: this.videoContent, // 分享描述, 请自行替换
            link: window.location.href, // 分享链接，根据自身项目决定是否需要split
            imgUrl: this.videoImg, // 分享图标, 请自行替换，需要绝对路径
            success: () => {
              ajax.doAction({
                url: '/user/shareSuccess',
                type: 'POST',
                successCallback:(data)=>{
                  // console.log(data)
                },
                errorCallback: (data)=> {
                  console.log('请求失败')
                }
              });
            },
            error: () => {
              alert('已取消分享')
            }
          }
          // 将配置注入通用方法
          wxapi.ShareAppMessage(option)
        }
      },
      destroyed() {
        clearInterval(this.time)
      }
    }
</script>

<style>
  .mime-video-detail-wrap .mime-cover-img{
    height: 186px;
  }
  .mime-video-detail-wrap .mime-video-content{
    padding-bottom: 50px;
  }
  .mime-video-detail-wrap .van-tab--active .van-ellipsis{
    color: #0085ca;
  }
  .mime-video-detail-wrap .video-recommend h2{
    font-size: 17px;
    font-weight: bold;
    color: #333;
    margin-bottom: 10px;
    margin-top: 24px;
  }
  .mime-video-detail-wrap .van-cell__title{
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .mime-video-detail-wrap .van-cell__title span{
    font-size: 18px;
    font-weight: bold;
  }
  .mime-video-detail-wrap .video-section-img{
    height: 73px;
  }
  .mime-video-detail-wrap .video-section-title{
    font-size: 15px;
    color: #9a9a9a;
    margin-bottom: 10px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp:2;
    -webkit-box-orient: vertical;
    font-weight: normal;
    line-height: 20px;
  }
  .mime-video-detail-wrap .video-section-time{
    font-size: 12px;
    color: #9a9a9a;
  }
  .mime-video-detail-wrap .video-section-time i{
    background-image: url("/static/images/shijian.png");
    background-position: center;
    background-repeat: no-repeat;
    display: inline-block;
    width: 11px;
    height: 11px;
    background-size: 100% 100%;
    vertical-align: middle;
    margin-right: 3px;
  }
  .mime-video-detail-wrap .video-section-list{
    margin-bottom: 20px;
    position: relative;
  }
  .mime-video-detail-wrap .video-section-list:last-of-type{
    margin-bottom: 0;
  }
  .mime-video-detail-wrap .video-section-list .video-section-list-icon{
    position: absolute;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
  }
  .mime-video-detail-wrap .video-section-list .video-section-list-icon label.playing{
    background-image: url("../../../static/images/bofang-ing-icon.png");
    width: 16px;
    height: 13px;
  }
  .mime-video-detail-wrap .video-section-list .video-section-list-icon label.lock{
    background-image: url("../../../static/images/bofang-suo-icon.png");
    width: 13px;
    height: 16px;
  }
  .mime-video-detail-wrap .video-section-list .video-section-list-icon label.try-to-see{
    background: #fff;
    border-radius: 5px;
    border:1px solid #38B17B;
    text-align: center;
    line-height: 22px;
    width: 38px;
    color: #38B17B;
    font-size: 12px;
  }
  .mime-video-detail-wrap .video-section-list .video-section-list-icon label{
    display: inline-block;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-position: center;
  }
  .mime-video-detail-wrap .video-section-list.active h4{
    color: #0085ca;
  }
  .mime-video-detail-wrap .video-section-list.active p{
    color: #0085ca;
  }
  .mime-video-detail-wrap .video-section-list.active h6{
    color:#0085ca;
  }
  .mime-video-detail-wrap .video-section-list.active p i{
    background-image: url("/static/images/shijian2.png");
  }
  .mime-video-detail-wrap .seeNumCount{
    font-size: 12px;
    color: #808080;
    font-weight: lighter;
    margin-top:15px;
    margin-bottom: 20px;
  }
  .mime-video-detail-wrap .seeNumCount-icon{
    display: inline-block;
    background: url("/static/images/index-info-icon1.png") no-repeat center;
    width: 10px;
    height: 12px;
    background-size: 100% 100%;
  }
  .mime-video-detail-wrap .seeNumCount .star-icon{
    display: inline-block;
    background-image: url("/static/images/star-icon.png");
    background-position: center;
    background-repeat: no-repeat;
    width: 15px;
    height: 15px;
    background-size: 100% 100%;
  }
  .mime-video-detail-wrap .seeNumCount .star-icon.active{
    background-image:  url("/static/images/star-icon-active.png");
  }
  .mime-video-detail-wrap .seeNumCount .thumbs-up-wrap{
    font-size:13px;
    color:#999;
  }
  .mime-video-detail-wrap .seeNumCount .thumbs-up-icon{
    display: inline-block;
    background-image: url("/static/images/index-college-icon.png");
    background-position: center;
    background-repeat: no-repeat;
    width: 15px;
    height: 14px;
    background-size: 100% 100%;
    margin-left: 10px;
  }
  .mime-video-detail-wrap .seeNumCount .thumbs-up-wrap.active{
    color: #0085ca;
  }
  .mime-video-detail-wrap .seeNumCount .thumbs-up-wrap.active .thumbs-up-icon{
    background-image: url("/static/images/index-college-icon2.png");
  }
  .mime-video-detail-wrap .videoComment-wrap h4{
    background: #f4f4f4;
    padding-left: 12px;
    line-height: 25px;
  }
  .mime-video-detail-wrap .videoCont h6{
    font-weight: normal;
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
  }
  .mime-video-detail-wrap .bofang-icon{
    background: url("/static/images/bofang-ing-icon.png") no-repeat center;
    display: inline-block;
    width: 16px;
    height: 13px;
    background-size: 100% 100%;
    position: absolute;
    right: 0;
    top:50%;
    transform: translateY(-50%);
  }

  .mime-video-detail-wrap .seeNumCount .course-price{
    padding-top: 10px;
  }
  .mime-video-detail-wrap .seeNumCount .course-price b{
    color: #33C37D;
    font-size: 18px;
  }
  .mime-video-detail-wrap .active-price{
    color: #33C37D;
    font-weight: bold;
    font-size: 18px;
    margin-left: 10px;
  }
  .mime-video-detail-wrap .seeNumCount s.active_course-price{
    font-size: 14px;
    color: #808080;
  }
  .mime-video-footer{
    position: fixed;
    height: 50px;
    line-height: 50px;
    width:100%;
    text-align: center;
    left:0;
    bottom: 0;
    font-size: 15px;
  }
  .mime-video-footer a{
    display: block;
    color: #fff;
  }
  .mime-video-footer a.go-study{
    background: #33C37D;
  }
  .mime-video-footer a.go-buy{
    background: #33C37D;
  }
  .mime-video-footer .see-free{
    background: #EEEEEE;
    color: #808080;
  }
</style>
